package com.example.rssreader.controller;

import com.example.rssreader.common.ApiResponse;
import com.example.rssreader.common.PageResponse;
import com.example.rssreader.dto.AddFeedRequest;
import com.example.rssreader.dto.FeedResponse;
import com.example.rssreader.service.RssFeedService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

/**
 * RSS源管理控制器
 * 提供RSS源的增删改查、同步等功能
 *
 * @author RSS Reader Team
 * @version 1.0.0
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/api/feeds")
@RequiredArgsConstructor
@Validated
@Tag(name = "RSS源管理", description = "RSS源的增删改查、同步等操作")
public class RssFeedController {

    private final RssFeedService rssFeedService;

    /**
     * 添加RSS源
     *
     * @param request 添加RSS源请求参数
     * @return 添加成功的RSS源信息
     */
    @PostMapping
    @Operation(summary = "添加RSS源", description = "添加新的RSS源，系统会自动验证URL有效性并抓取基本信息")
    public ApiResponse<FeedResponse> addFeed(
            @Valid @RequestBody AddFeedRequest request) {

        log.info("接收添加RSS源请求，URL: {}", request.getUrl());

        try {
            FeedResponse response = rssFeedService.addFeed(request);
            log.info("RSS源添加成功，ID: {}", response.getId());
            return ApiResponse.success(response, "RSS源添加成功");

        } catch (Exception e) {
            log.error("添加RSS源失败，URL: {}, 错误: {}", request.getUrl(), e.getMessage(), e);
            return ApiResponse.error("添加RSS源失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询RSS源列表
     *
     * @param page 页码，从1开始，默认为1
     * @param size 每页大小，默认为10
     * @return RSS源分页列表
     */
    @GetMapping
    @Operation(summary = "分页查询RSS源列表", description = "获取RSS源列表，支持分页查询")
    public ApiResponse<PageResponse<FeedResponse>> getFeeds(
            @Parameter(description = "页码，从1开始")
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码必须大于0") Integer page,

            @Parameter(description = "每页大小，范围1-100")
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页大小必须大于0") Integer size) {

        log.debug("接收查询RSS源列表请求，页码: {}, 每页大小: {}", page, size);

        try {
            // 限制每页最大数量
            if (size > 100) {
                size = 100;
            }

            PageResponse<FeedResponse> response = rssFeedService.getFeeds(page, size);
            return ApiResponse.success(response, "查询成功");

        } catch (Exception e) {
            log.error("查询RSS源列表失败: {}", e.getMessage(), e);
            return ApiResponse.error("查询RSS源列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取RSS源详情
     *
     * @param id RSS源ID
     * @return RSS源详细信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取RSS源详情", description = "根据ID获取RSS源的详细信息")
    public ApiResponse<FeedResponse> getFeedById(
            @Parameter(description = "RSS源ID")
            @PathVariable @NotNull(message = "RSS源ID不能为空") Long id) {

        log.debug("接收获取RSS源详情请求，ID: {}", id);

        try {
            FeedResponse response = rssFeedService.getFeedById(id);
            return ApiResponse.success(response, "查询成功");

        } catch (Exception e) {
            log.error("获取RSS源详情失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            return ApiResponse.error("获取RSS源详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新RSS源信息
     *
     * @param id          RSS源ID
     * @param title       新标题
     * @param description 新描述
     * @return 更新后的RSS源信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新RSS源信息", description = "更新RSS源的标题和描述信息")
    public ApiResponse<FeedResponse> updateFeed(
            @Parameter(description = "RSS源ID")
            @PathVariable @NotNull(message = "RSS源ID不能为空") Long id,

            @Parameter(description = "新标题")
            @RequestParam(required = false) String title,

            @Parameter(description = "新描述")
            @RequestParam(required = false) String description) {

        log.info("接收更新RSS源请求，ID: {}", id);

        try {
            FeedResponse response = rssFeedService.updateFeed(id, title, description);
            log.info("RSS源更新成功，ID: {}", id);
            return ApiResponse.success(response, "RSS源更新成功");

        } catch (Exception e) {
            log.error("更新RSS源失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            return ApiResponse.error("更新RSS源失败: " + e.getMessage());
        }
    }

    /**
     * 删除RSS源
     *
     * @param id RSS源ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除RSS源", description = "删除指定的RSS源及其所有文章")
    public ApiResponse<Void> deleteFeed(
            @Parameter(description = "RSS源ID")
            @PathVariable @NotNull(message = "RSS源ID不能为空") Long id) {

        log.info("接收删除RSS源请求，ID: {}", id);

        try {
            rssFeedService.deleteFeed(id);
            log.info("RSS源删除成功，ID: {}", id);
            return ApiResponse.success(null, "RSS源删除成功");

        } catch (Exception e) {
            log.error("删除RSS源失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            return ApiResponse.error("删除RSS源失败: " + e.getMessage());
        }
    }

    /**
     * 手动同步RSS源
     *
     * @param id RSS源ID
     * @return 同步结果信息
     */
    @PostMapping("/{id}/sync")
    @Operation(summary = "手动同步RSS源", description = "立即同步指定RSS源的最新文章")
    public ApiResponse<String> syncFeed(
            @Parameter(description = "RSS源ID")
            @PathVariable @NotNull(message = "RSS源ID不能为空") Long id) {

        log.info("接收手动同步RSS源请求，ID: {}", id);

        try {
            String result = rssFeedService.syncFeed(id);
            log.info("RSS源同步成功，ID: {}, 结果: {}", id, result);
            return ApiResponse.success("同步成功", result);

        } catch (Exception e) {
            log.error("同步RSS源失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            return ApiResponse.error("同步RSS源失败: " + e.getMessage());
        }
    }

    /**
     * 搜索RSS源
     *
     * @param keyword 搜索关键词
     * @param page    页码，从1开始，默认为1
     * @param size    每页大小，默认为10
     * @return RSS源搜索结果
     */
    @GetMapping("/search")
    @Operation(summary = "搜索RSS源", description = "根据关键词搜索RSS源")
    public ApiResponse<PageResponse<FeedResponse>> searchFeeds(
            @Parameter(description = "搜索关键词")
            @RequestParam @NotBlank(message = "搜索关键词不能为空") String keyword,

            @Parameter(description = "页码，从1开始")
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码必须大于0") Integer page,

            @Parameter(description = "每页大小，范围1-100")
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页大小必须大于0") Integer size) {

        log.debug("接收搜索RSS源请求，关键词: {}, 页码: {}, 每页大小: {}", keyword, page, size);

        try {
            // 限制每页最大数量
            if (size > 100) {
                size = 100;
            }

            PageResponse<FeedResponse> response = rssFeedService.searchFeeds(keyword, page, size);
            return ApiResponse.success(response, "搜索成功");

        } catch (Exception e) {
            log.error("搜索RSS源失败，关键词: {}, 错误: {}", keyword, e.getMessage(), e);
            return ApiResponse.error("搜索RSS源失败: " + e.getMessage());
        }
    }

    /**
     * 同步所有RSS源
     *
     * @return 同步结果统计信息
     */
    @PostMapping("/sync-all")
    @Operation(summary = "同步所有RSS源", description = "批量同步所有RSS源的最新文章")
    public ApiResponse<String> syncAllFeeds() {

        log.info("接收同步所有RSS源请求");

        try {
            String result = rssFeedService.syncAllFeeds();
            log.info("所有RSS源同步完成，结果: {}", result);
            return ApiResponse.success("同步完成", result);

        } catch (Exception e) {
            log.error("同步所有RSS源失败: {}", e.getMessage(), e);
            return ApiResponse.error("同步所有RSS源失败: " + e.getMessage());
        }
    }

    /**
     * 验证RSS源URL
     *
     * @param url RSS源URL
     * @return 验证结果信息
     */
    @GetMapping("/validate")
    @Operation(summary = "验证RSS源URL", description = "检查RSS源URL是否有效")
    public ApiResponse<String> validateFeedUrl(
            @Parameter(description = "RSS源URL")
            @RequestParam @NotBlank(message = "RSS源URL不能为空") String url) {

        log.debug("接收验证RSS源URL请求，URL: {}", url);

        try {
            String result = rssFeedService.validateFeedUrl(url);
            return ApiResponse.success("验证完成", result);

        } catch (Exception e) {
            log.error("验证RSS源URL失败，URL: {}, 错误: {}", url, e.getMessage(), e);
            return ApiResponse.error("验证RSS源URL失败: " + e.getMessage());
        }
    }

    /**
     * 获取RSS源统计信息
     *
     * @return RSS源统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取RSS源统计信息", description = "获取RSS源的统计数据")
    public ApiResponse<Object> getFeedStatistics() {

        log.debug("接收获取RSS源统计信息请求");

        try {
            Object statistics = rssFeedService.getFeedStatistics();
            return ApiResponse.success(statistics, "查询成功");

        } catch (Exception e) {
            log.error("获取RSS源统计信息失败: {}", e.getMessage(), e);
            return ApiResponse.error("获取RSS源统计信息失败: " + e.getMessage());
        }
    }

}